package com.nettyRpc.provider.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

/**
 * 服务端请求 SocketChannel tcp-socket
 */
public class NettyServer {

    public void bind(int port) {
        EventLoopGroup worker = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(worker)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 50000)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) {
                            ChannelPipeline ph = socketChannel.pipeline();
                            ph.addLast(new ObjectDecoder(1024*1024, ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
                            ph.addLast(new ObjectEncoder());
                            //添加NettyServerHandler，用来处理Server端接收和处理消息的逻辑
                            ph.addLast(new DubboChannelHandler());
                        }
                     });

            // 服务器绑定端口监听
            ChannelFuture f = b.bind(port).sync();
            if (f.isSuccess()) {
                System.err.println("启动Netty服务成功，端口号：" + port);
            }
            // 监听服务器关闭监听
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            System.err.println("启动Netty服务异常，异常信息：" + e.getMessage());
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
        }
    }
}
